package com.lion.common.spring.enhancers.header;

import com.chris.dev.base.libs.v1.http.protocols.HttpHeader;
import com.lion.common.base.contexts.CommonRequestContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.List;

/**
 * 自定义参数解析器，用于解析HttpHeader类型的参数
 * 接口方法可以显式声明HttpHeader参数
 */
public class HttpHeaderArgumentResolver extends RequestResponseBodyMethodProcessor {

    public HttpHeaderArgumentResolver(List<HttpMessageConverter<?>> converters) {
        super(converters);
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(HttpHeader.class) ||
                super.supportsParameter(parameter);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {

        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);

        // 处理HttpHeader类型参数
        if (parameter.getParameterType().equals(HttpHeader.class)) {
            if (request != null) {
                return request.getAttribute("X-Http-Headers");
            } else {
                //可能多余
                return CommonRequestContextHolder.getHeader();
            }
        }
        // 其他参数走默认处理
        return super.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
    }
}